<template>
  <div class="comments-section">
    <h3>💬 评论区</h3>

    <el-input
      v-model="newComment"
      type="textarea"
      placeholder="写下你的评论..."
      rows="3"
    />
    <el-button
      type="primary"
      size="small"
      class="mt-2"
      @click="submitComment"
      :disabled="!newComment.trim()"
    >发表评论</el-button>

    <el-divider />

    <div v-if="comments.length">
      <CommentItem
        v-for="comment in comments"
        :key="comment.id"
        :comment="comment"
      />
    </div>
    <p v-else class="no-comment">还没有评论，快来抢沙发吧！</p>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import { useUserStore } from '@/stores/user'
import CommentItem from "./CommentItem.vue"

const userStore = useUserStore()

const props = defineProps({
  postId: Number,
});

const comments = ref([]);
const newComment = ref("");

const formatDate = (time) => {
  const d = new Date(time);
  return d.toLocaleString();
};

// 获取评论列表
const fetchComments = async () => {
  if (!props.postId) return;
  const res = await request.get(`/api/comments/${props.postId}`);
  if (res.code === 200) {
    comments.value = res.data;
  }
};

// 发表评论
const submitComment = async () => {
  const token = localStorage.getItem("token");
  if (!token) {
    ElMessage.warning("请先登录再发表评论");
    return;
  }

  const res = await request.post("/api/comments", {
    postId: props.postId,
    content: newComment.value.trim(),
    userId: userStore.userInfo.id,
  });

  if (res.code === 200) {
    ElMessage.success("评论成功");
    newComment.value = "";
    fetchComments();
  } else {
    ElMessage.error(res.message);
  }
};

onMounted(fetchComments);
watch(() => props.postId, fetchComments);
</script>

<style scoped>
.comments-section {
  margin-top: 40px;
}
.comment-item {
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}
.author {
  font-weight: bold;
  color: #409eff;
}
.content {
  margin: 5px 0;
}
.time {
  font-size: 12px;
  color: #aaa;
}
.no-comment {
  color: #999;
  font-style: italic;
}
</style>
